<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      .div{
			width: 300px;
			height: 300px;
			background-color: #0C86EF;
		}
		.div2{
			width: 300px;
			height: 300px;
			background-color: #D2379B;
		}
    </style>
</head>
<body>
	<img src="https://images.weserv.nl/?url=https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2881176356.webp" id="scream" crossorigin="">
	<canvas id="myCanvas" style="display: none;"></canvas> 
	
		
	
	<script src="./lib/jquery-3.6.1.min.js"></script>
	<script>
		var img = $('#scream').get(0); //图片节点

        // 获取图片色rgb颜色值
        function getImageColor(img) {
			var canvas = document.getElementById("myCanvas");  //canvas元素
            canvas.width = img.width;
            canvas.height = img.height;
        
            var context = canvas.getContext("2d");
        
            context.drawImage(img, 0, 0, canvas.width, canvas.height);
        
            // 获取像素数据
            var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
            console.log(imgData);

            var r = 0, g = 0, b = 0, a = 0;
            // 取所有像素的平均值
            for (var row = 0; row < img.height; row++) {
                for (var col = 0; col < img.width; col++) {
                    r += imgData.data[((img.width * row) + col) * 4];
                    g += imgData.data[((img.width * row) + col) * 4 + 1];
                    b += imgData.data[((img.width * row) + col) * 4 + 2];
                }
            }
        
            // 求取平均值
            r /= (canvas.width * canvas.height);
            g /= (canvas.width * canvas.height);
            b /= (canvas.width * canvas.height);
        
            // 将最终的值取整
            r = Math.round(r);
            g = Math.round(g);
            b = Math.round(b);
        
			let rgba = {r:r,g:g,b:b};
			console.log(rgba);
            return rgba;
        }
		console.log(getImageColor(img));
	</script>
</body>
</html>